﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using log4net;
using Microsoft.Office.Core;
using MSProject = Microsoft.Office.Interop.MSProject;
using PSLibrary = Microsoft.Office.Project.Server.Library;

using DataDesign.MPP.Utilities;
using DataDesign.MPP.ServerManager;
using DataDesign.MPP.ServerManager.WebSvcCustomFields;
using DataDesign.MPP.ServerManager.WebSvcLookupTable;
using DataDesign.MPP.ServerManager.WebSvcProject;
using DataDesign.MPP.ServerManager.WebSvcResource;
using DataDesign.MPP.AddIn.Forms;

namespace DataDesign.MPP.AddIn
{
	// Code update.
    public class ButtonMenu
    {        
        private static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private CommandBar cmdBar;                      // MS Project Menu Tools
        private CommandBarButton btnSearchProject;      // Search Project Button
		private CommandBarButton btnInputFields=null;    //Open a form and Input fields 

        public object AddInInst { get; set; }
        public MSProject.Application MSProjectApplication { get; set; }
        public MSProject.Project MSProject { get; set; }        

        public const string COMMAND_BAR_NAME = "MPP"; //"MPP";
        public const string SEARCH_PROJECT_BUTTON_NAME = "SearchProject";
		public const string OPEN_INPUT = "Open Input";
        public ButtonMenu(MSProject.Application application, object addIn)
        {
            MSProjectApplication = application;
            AddInInst = addIn;            
        }

        public bool AddButton()
        {
            try
            {
                // Check to see there is menu named CommandBarName
                // If not existed, add new menu named CommandBarName at the last
                // Then add 1 command action at the bottom of the menu

                logger.Debug("Begin GetCommandBar");
                GetCommandBar();
                logger.Debug("Begin CreateButton");                                
                CreateButton();
                
                return true;
            }
            catch (Exception ex)
            {
                logger.Error("ERROR AddButton", ex);
                HelperAddIn.ShowError(ex);
                return false;
            }            
        }

        private void GetCommandBar()
        {            
            try
            {
                foreach (CommandBar cmd in MSProjectApplication.CommandBars)
                {
                    logger.DebugFormat("CommandBar: {0}", cmd.Name);
                    if (cmd.Name.Equals(COMMAND_BAR_NAME))
                    {
                        cmdBar = cmd;
                        return;
                    }
                    foreach (CommandBarControl control in cmd.Controls)
                    {
                        logger.DebugFormat("CommandBar: {0}", control.Caption);
                        if (control.Caption.Equals(COMMAND_BAR_NAME))
                        {
                            cmdBar = ((CommandBarPopup)control).CommandBar;
                            return;
                        }
                    }
                }

                logger.DebugFormat("Can not find CommandBar {0}. Add new one", COMMAND_BAR_NAME);
                cmdBar = MSProjectApplication.CommandBars.Add(COMMAND_BAR_NAME, MsoBarPosition.msoBarTop, false, true);
                                
            }
            catch (Exception ex)
            {
                logger.Error("ERROR GetCommandBar", ex);
                throw;
            }            
        }

        private void CreateButton()
        {
            try
            {                
                btnSearchProject = (CommandBarButton)cmdBar.Controls.Add(MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true);
                btnSearchProject.Caption = SEARCH_PROJECT_BUTTON_NAME;                
                btnSearchProject.Style = MsoButtonStyle.msoButtonCaption;
                btnSearchProject.Click += new _CommandBarButtonEvents_ClickEventHandler(btnSearchProject_Click);          
                //btnSearchProject.Click += new _CommandBarButtonEvents_ClickEventHandler(btnAction_Click);          
				btnInputFields = (CommandBarButton)cmdBar.Controls.Add(MsoControlType.msoControlButton,1,"",cmdBar.Controls.Count+1,false);
                btnInputFields.Caption = OPEN_INPUT;
                btnInputFields.Style = MsoButtonStyle.msoButtonCaption;
                btnInputFields.Click += new _CommandBarButtonEvents_ClickEventHandler(btnInputFields_Click);

                cmdBar.Visible = true;
            }
            catch (Exception ex)
            {
                logger.Error("ERROR CreateButton", ex);
                throw;
            }
        }

 		void btnInputFields_Click(CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                MSProject = MSProjectApplication.ActiveProject;
                if (MSProject==null)
                {
                    return;
                }

                Forms.frmOpenInput frmInput=new Forms.frmOpenInput(MSProject,MSProjectApplication);
                if (frmInput.ShowDialog()==DialogResult.OK)
                {
                    
                }
            }
            catch (Exception ex)
            {

                HelperAddIn.ShowError(ex.Message);
            }
            
        }
        void btnSearchProject_Click(CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                FormSearchProject frmSearchProject = new FormSearchProject(MSProjectApplication);
                frmSearchProject.ShowDialog();                
            }
            catch (Exception ex)
            {
                logger.Error("ERROR btnSearchProject_Click", ex);
                HelperAddIn.ShowError(ex);
            }
        }

        void btnAction_Click(CommandBarButton Ctrl, ref bool CancelDefault)
        {
            try
            {
                HelperAddIn.ShowInfo("Action");

                MSProject = MSProjectApplication.ActiveProject;

                HelperAddIn.ShowInfo(string.Format("Current Project Name: {0}", MSProject.Name));
                
                foreach (MSProject.Task task in MSProject.Tasks)
                {
                    logger.DebugFormat("Name: {0}", task.Name);
                    logger.DebugFormat("Resource Name: {0}", task.ResourceNames);
                }
                
                //Read all projects on PS
                ProjectDataSet dsProject = ProjectManager.GetAllProjectsOnServer();
                foreach (ProjectDataSet.ProjectRow projectRow in dsProject.Project)
                {
                    logger.DebugFormat("ProjectName: {0}, ProjectGuid: {1}", projectRow.PROJ_NAME, projectRow.PROJ_UID);
                    ProjectDataSet project = ProjectManager.GetProjectByGuid(projectRow.PROJ_UID);
                    foreach(ProjectDataSet.TaskRow taskRow in project.Task)
                    {
                        //logger.DebugFormat("TaskName: {0}, TaskResourceName: {1}", taskRow.TASK_NAME, taskRow.);
                    }
                }

                ResourceDataSet.ResourcesRow currentUser = ResourceManager.GetCurrentUser();

                var dsResource = ResourceManager.GetAllResourcesOnServer();
                string customFieldName = "DepartmentName";
                //foreach (WebSvcResource.ResourceDataSet.ResourcesRow resourceRow in dsResource.Resources)
                //{
                //    string value = ResourceManager.GetValueForCustomFieldOfResource(resourceRow, customFieldName);
                //    logger.DebugFormat("Value of custom field {0} of resource {1} is {2}", customFieldName, resourceRow.RES_NAME, value);
                //}

                var dicLookupTable = ResourceManager.GetLookupTableDictionaryForCustomField(customFieldName, ResourceManager.EntityType.ResourceEntity);
                logger.DebugFormat("dicLookupTable Count: {0}", dicLookupTable.Count);
                foreach (ResourceDataSet.ResourcesRow resourceRow in dsResource.Resources)
                {
                    Guid valueGuid = ResourceManager.GetGuidValueForCustomFieldOfResource(resourceRow, customFieldName);
                    logger.DebugFormat("Value of custom field {0} of resource {1} is {2}", customFieldName, resourceRow.RES_NAME, dicLookupTable[valueGuid]);
                }
                
                var dsCustomFields = ResourceManager.GetAllCustomFieldsOnServer();
                var dsLookupTable = ResourceManager.GetAllLookupTableOnServer();
                
            }
            catch (Exception ex)
            {
                logger.Error("ERROR btnAction_Click", ex);
                HelperAddIn.ShowError(ex);
            }
        }

        // Convert DataSet to MSProject.Project for easy-read-data
        //public static MSProject.Project
    }

}
